# -*- coding: utf-8 -*-
"""
Created on Sat Oct  9 18:05:19 2021

@author: 刘长奇
"""

import numpy as np
from sklearn import datasets
import matplotlib.pyplot as plt
import random
from sklearn.metrics import confusion_matrix
import seaborn as sns
from sklearn.neural_network import MLPClassifier

# generate sample data
np.random.seed(0)
data, target = datasets.make_moons(200, noise=0.20)

train=[]
train_label=[]
test=[]
test_label=[]
num=int(np.shape(data)[0]*0.7)
arg=random.sample(range(0,np.shape(data)[0]),num)

for i in range(num):
    train.append(data[arg[i]])
    train_label.append(target[arg[i]])
for i in range(np.shape(data)[0]):
    if i in arg:
        continue
    else:
        test.append(data[i])
        test_label.append(target[i])
test=np.array(test)
train=np.array(train)
train_label=np.array(train_label)
clf_class= MLPClassifier(solver='lbfgs', alpha=1e-5,hidden_layer_sizes=(200,200), random_state=1)
clf_class.fit(train,train_label)
y_pred=[]
j=0
for i in range(np.shape(test)[0]):
    y_pred.append(clf_class.predict([test[i]]))
for i in range(np.shape(test)[0]):
    if y_pred[i]==test_label[i]:
        j=j+1
print('神经网络训练的测试集准确度：',j/np.shape(test)[0])    #0.93~0.98;自己编写的程序准确率为0.82
confusion_matrix_result=confusion_matrix(y_pred,test_label)
#数据可视化
plt.subplot(1,2,1)
plt.title('the test data')
plt.scatter(test[:,0],test[:,1],c=test_label)
plt.subplot(1,2,2)
plt.title('the nets result')
plt.scatter(test[:,0],test[:,1],c=y_pred)
plt.colorbar()

#错误数据可视化
plt.figure(figsize=(8,6))
sns.heatmap(confusion_matrix_result,annot=True,cmap='Blues')
plt.xlabel('Predicted labels')
plt.ylabel('True labels')
plt.title('confusion_matrix')
plt.show()

    
    
    
    
    
    
    